/*
 * @Descripttion:
 * @Author: voanit
 * @Date: 2020-08-30 22:59:10
 * @LastEditors: voanit
 * @LastEditTime: 2022-01-02 11:03:46
 */
import router, { asyncRoutes, resetRouter } from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

/* 只要路由值[path]发生改变就会触发这个钩子函数，跳转之前  next是一个函数 表示放行 */
router.beforeEach(async(to, from, next) => {
  // console.log('beforeEach====')
  // start progress bar
  NProgress.start()

  /*
  有token
    是登录=》首页
    不是登录页=》放行
  没有token
    是不是白名单=>放行
    不是白名单=》登录
   */

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken() //  获取token
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      // next({ path: '/' })
      // NProgress.done()
    } else {
      // await store.dispatch('user/getInfo')
      //  有token去的不是登录页=》放行
      // next()
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
        // get user info
          const { roles: { menus }} = await store.dispatch('user/getInfo')
          // console.log(menus)
          // 步骤说明
          // 1.现在获取当前用户所拥有的权限：menus
          // 2.当前的menus去所有的那8个中做筛选并获取筛选之后的
          var newRoutes = asyncRoutes.filter(item => {
            var name = item.children[0].name
            return menus.includes(name)
          })
          // 保证的是,左侧菜单有这几个权限,理由规则中没有
          store.commit('menu/setMenuList', newRoutes)
          // 重置路由
          resetRouter()
          // 防止刷新跳转404
          newRoutes.push({ path: '*', redirect: '/404', hidden: true })
          // 动态生成路由规则
          router.addRoutes(newRoutes)
          // router.addRoutes(asyncRoutes)
          next(to.path)
        } catch (error) {
        // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      // }
      }
    }
  } else {
    //  没有token
    /* has no token*/
    // if (whiteList.indexOf(to.path) !== -1) {  isNaN   includes优于indexOf
    if (whiteList.includes(to.path)) {
      //  说明在白名单中有
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

/* 跳转之后在执行 */
router.afterEach(() => {
  // console.log('afterEach====')
  // finish progress bar
  NProgress.done()
})
